package com.dabai.iot.core.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dabai.iot.common.enums.DataType;
import com.dabai.iot.common.model.DeviceInfo;
import com.dabai.iot.common.model.IotMqttMessage;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * 用于组装服务端订阅使用的报文数据
 *
 * @author kev1n
 */
@Slf4j
public class ServerMessageHandler {

    /**
     * 组装服务端订阅使用的设备状态数据
     */
    public static JSONObject assembleStatusToServerPayload(String productKey, String deviceSn, String status, Date now) {
        return new JSONObject()
            .fluentPut("type", "status")
            .fluentPut("productKey", productKey)
            .fluentPut("deviceSn", deviceSn)
            .fluentPut("status", status)
            .fluentPut("generateTime", now);
    }

    /**
     * 组装服务端订阅使用的设备消息数据
     */
    public static JSONObject assembleMessageToServerPayload(DeviceInfo deviceInfo, IotMqttMessage mqttMessage, String payload) {
        String dataType = mqttMessage.dataType();
        String topic = mqttMessage.topic();
        Integer qos = mqttMessage.qos();

        JSONObject contentObj = new JSONObject();
        contentObj.put("topic", topic);

        // 判断数据格式
        if (DataType.JSON.getValue().equals(dataType)) {
            contentObj.put("payload", JSON.parseObject(payload));
        } else { // Plaintext
            contentObj.put("payload", payload);
        }

        contentObj.put("qos", qos);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "data");
        jsonObject.put("productKey", deviceInfo.productKey());
        jsonObject.put("deviceSn", deviceInfo.deviceSn());
        jsonObject.put("content", contentObj);
        jsonObject.put("generateTime", mqttMessage.reportTime());

        return jsonObject;
    }

}
